const Product = require('../models/products.model.js');
//增
exports.create=function(req,res,next){
    const product=new Product(req.body);
    product.save().then(data=>{
        res.json(data);
    })
};

//删
exports.remove=function(req,res,next){
    var id=req.params.id;
    Product.findByIdAndDelete(id,(err,data)=>{
        res.json(data)
    })
};

//改
exports.update = function(req,res,next){
    var id = req.params.id;
    Product.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
        res.json(data);
    });
};

//查

exports.list = function(req,res,next){
    var page = req.body.page ? req.body.page : 1;
    var limit = req.body.limit ? req.body.limit : 5;
  
    var queryCondition = {};
    if (req.body.name && req.body.name.trim().length > 0) {
        name = req.body.name;
        queryCondition = {
          name: new RegExp(name,'i')
        };
      }
      console.log(typeof limit);
    
      Product.paginate(queryCondition, { page: +page, limit: +limit }, function(err, result) {
        result.rows=result.docs;
        res.json(result);
      });
};

exports.getData = function(req, res, next) {
    var id = req.params.id;
    Product.findById(id).then(data => {
        res.json(data);
    })
};

exports.removes = function(req, res, next) {
    var ids = req.body.ids.split(',');
    Product.remove({ _id: { $in: ids } }).then(data => {
        res.json({ message: '数据删除成功', status: 200 });
    });
}